package com.juhuixing.common.base;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;

/**
 * 功能描述:
 * @author: 刘猛
 * @date: 2019/3/19 14:01
 **/
@Slf4j
public class BaseController {


    private static ThreadLocal<ServletRequest> currentRequest = new ThreadLocal<ServletRequest>();

    @ModelAttribute
    protected void initReqAndRep(HttpServletRequest request, HttpServletResponse response) {
        currentRequest.set(request);
    }

    protected HttpServletRequest request() {
        return (HttpServletRequest) currentRequest.get();
    }

    /**
     * 打印请求的信息
     */
    protected void printRequestInfo() {
        StringBuilder paramBuilder = new StringBuilder();
        String requestInfo = "requestUrl:s%\nrequestParam:s%\nAuthorization:s%";
        //获取所有的请求参数
        Enumeration<String> paraNames = request().getParameterNames();
        while (paraNames.hasMoreElements()) {
            String thisName = paraNames.nextElement();
            String thisValue = request().getParameter(thisName);
            paramBuilder.append(thisName).append("=").append(thisValue).append("&");
        }
        String param = StringUtils.substringBeforeLast(paramBuilder.toString(), "&");
        //获取header中的用户信息
        String access_token = request().getHeader("access_token");
        log.error(String.format(requestInfo, request().getRequestURI(), param, access_token));
    }

    /**
     * 获取当前登录的用户
     *
     * @return Long UserName
     */
    protected String getCurrentUserName() {
        String username = request().getHeader("username");
        return username;
    }

    protected String getSource() {
        return request().getHeader("source");
    }
}
